
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()

var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(data) {
    let url = 'https://api.wenfree.cn/?s=App.Autojs_Hema.Hema'
    var headers = {
        "Content-Type": "application/json"
    };
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data);
        return data;
    }
};


function getTitleConent(){
    if ( currentActivity() == "com.wudaokou.hippo.search.SearchActivity" ){
        log("进入搜索界面")
        //没有分类就返回
        if ( !appInfo.category){
            return true;
        }

        try {
            appInfo['search_key'] = id("tv_search_editable_keyword").findOne(200).text()

            let allprice = textMatches("¥.*").find();
            // log(allprice[0].text())
            for (let i=0;i<allprice.length;i++){
                let price = allprice[i].text()
                
                // 假设 allprice[i] 是当前元素，获取其兄弟节点的 text 内容作为 title
                function getTitle(objects){
                    let siblings = objects.parent().children();
                    let title = '';
                    for (let j = 0; j < siblings.length; j++) {
                        let siblingText = siblings[j].text();
                        if (siblingText.length > 6) {
                            title += siblingText + ' ';
                            return title.trim();
                        }
                    }
                }
                let title = getTitle(allprice[i]);
                log(title, price)
        
                var postData = {
                    "city": "北京",
                    "local": appInfo.local,
                    "category": appInfo.category,
                    "category2": appInfo.category2,
                    "search_key": appInfo['search_key'],
                    "title": title,
                };
                
                if (price.includes('/')) {
                    postData['price'] = price;
                } else {
                    postData['vip'] = price;
                }
                f.postJson(postData)
            }
        }catch (error) {
            log('获取标题内容失败', error);
        }
        
        if (f.ms({"textMatches":"还有.*个已售完商品"}, true ) ){
            //这里要把这个点开
        }else
        if( f.ms({"textMatches":"我可是有底线的哦||正在加载更多||RECOMMEND"}) ){
            return true
        }
    
        f.moveTo(0.5,0.8,0.5,0.5,1000)
    }
}





// if (getTitleConent()) {
//     back();
// }

var appInfo = {
    category: '',
    category2: '',
    search_key: '',
    title: '',
    price: '',
}
var storage = storages.create("hema");

function todoMain(){
    if ( f.ms({text:"分类"}) ){
        log("进入首页")
        let current_category = descMatches("已选中.*").findOne(200);
        if( current_category ){
            appInfo['category'] = current_category.desc().replace("已选中，","")
            log("已选中>>", appInfo['category'] )
            if (appInfo['category'] == '为你推荐' ){
                f.moveTo(0.5, 0.8, 0.5, 0.3, 1000)
                return
            }
        }
    }
    
    let allButton = className("android.widget.Button").depth('20').find();
    if(allButton){
        let moveKey = true
        for (let i=0;i<allButton.length;i++){
            let button = allButton[i];
            log(button.desc())
            // 原：!look.includes(button.desc()) → ES5 兼容写法
            if ( look.indexOf(button.desc()) === -1 ){  // 修改点1：includes → indexOf
                // 检查按钮中心点是否超出屏幕范围
                const bounds = button.bounds();
                const centerX = bounds.centerX();
                const centerY = bounds.centerY();
                const screenWidth = device.width;
                const screenHeight = device.height;

                if (centerX < 0 || centerX > screenWidth || centerY < 0 || centerY > screenHeight-300) {
                    // 按钮中心点超出屏幕范围，向上滑动一点儿
                    f.moveTo(0.5, 0.8, 0.5, 0.3, 1000);
                    break;
                }else{
                    appInfo['category2'] = button.desc()
                    f.clickObj(button, 5, button.desc())
                    look.push(button.desc())
                    storage.put("look", look);
                    moveKey = false
                    break;
                }
            }
        }
        if(moveKey){
            f.moveTo(0.5,0.8,0.5,0.5,1000)
        }
    }else{
        log("没有更多分类了")
        exit()
    }
}


function main(){
    f.active("com.wudaokou.hippo", 10)

    let titleRecord = ""
    let titleCount = 0
    while (1){
    
        if ( !appInfo.local ){
            f.ms({ "text": "首页" }, true)
        }
    
        if (f.ms({ "id": 'home_page_titlebar_location_text' })) {
            log("进入首页")
            let local = id("home_page_titlebar_location_text").findOne(200);
            if (local) {
                appInfo['local'] = local.text()
                log("所在地", appInfo['local'])
            }
    
            f.ms({ "text": "分类" }, true)
        }
    
        todoMain()
        if( getTitleConent() ){
            back()
            sleep(5000)
        }
        // if( titleRecord == appInfo['category2'] ){
        //     titleCount++
        //     log("当前分类",titleRecord,"次数",titleCount)
        //     if ( titleCount > 9 ){
        //        back()
        //        sleep(5000)
        //     }
        // }else{
        //     titleRecord = appInfo['category2']
        //     titleCount = 0
        // }
    }
}






// //批查打印app参数
function printAll(ways) {
    if (!ways) {
        ways = 'className'
    }
    if (ways = 'className') {
        var all_Info = classNameMatches(/.*/).find();
    } else
        if (ways == 'text') {
            var all_Info = textMatches(/.*/).find();
        } else
            if (ways == 'id') {
                var all_Info = idMatches(/.*/).find();
            } else {
                eval('var all_Info = ' + ways + '.find();')
            }

    if (all_Info) {
        for (var i = 0; i < all_Info.length; i++) {
            var d = all_Info[i];
            log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"', "depth->" + d.depth(),
                d.bounds().centerX(), d.bounds().centerY(), `drawingOrder:${d.drawingOrder()}`)
        }
    } else {
        log('没有找到任何相关的节点')
    }
}



var used_category = [];
used_category = storage.get("used_category") || [];

var categories_ = [
    '水果鲜花',
    '蔬菜豆制品',
    '肉禽蛋',
    '海鲜水产',
    '粮油调味',
    '熟食卤味',
    '冻品面点',
    '乳品烘焙',
    '酒水冲饮',
    '休闲零食',
    '日用清洁',
    '个护美妆',
    '母.*婴',
    '保健.*'
];
// // 新增：分类选择界面函数
function selectCategory() {
    if (categories_.length === 0) {
        log("未获取到分类数据");
        return;
    }
    // 显示分类列表供用户选择（返回选中项的索引）
    const selectedIndex = dialogs.select("请选择要添加的分类", categories_);
    if (selectedIndex === -1) { // 用户点击取消
        log("已取消选择");
        return;
    }
    const selectedCategory = categories_[selectedIndex];
    // 检查是否已存在，避免重复添加
    if (used_category.indexOf(selectedCategory) < 0) {
        used_category.push(selectedCategory);
        storage.put("used_category", used_category); // 存储更新后的数组
        log(`已添加分类：${selectedCategory}，当前已选：${used_category}`);
    } else {
        log(`分类 ${selectedCategory} 已存在，无需重复添加`);
    }
}

// 这里写个函数，把分类数据拿出来used_category ，然后调用 显示出来，再询问，是否清除掉 used_category的记录
function manageUsedCategory() {
    // 显示当前已选分类
    if (used_category.length === 0) {
        dialogs.alert("分类记录", "当前没有已选择的分类记录");
    } else {
        // 拼接显示内容（换行分隔）
        const categoryList = used_category.join("\n");
        dialogs.alert("已选分类记录", `当前已选择的分类：\n${categoryList}`);
    }
    
    // 提供操作选项：添加分类、清除分类、取消
    const action = dialogs.select("操作选择", ["添加分类", "清除分类", "取消"]);
    if (action === -1) { // 用户点击取消
        toast("已取消操作");
        return;
    }

    switch (action) {
        case 0: // 添加分类
            if (typeof selectCategory === "function") {
                selectCategory(); // 调用已有的分类选择函数（需确保该函数未被注释）
                manageUsedCategory()
            } else {
                toast("添加分类功能未实现");
            }
            break;
        case 1: // 清除分类
            const isClear = dialogs.confirm("清除确认", "是否要清除所有已选分类记录？");
            if (isClear) {
                used_category = [];
                storage.remove("used_category"); // 清除存储
                toast("已清除所有分类记录");
            } else {
                toast("已取消清除操作");
            }
            break;
        case 2: // 取消
            toast("已取消操作");
            break;
    }
}

printAll()
// exit()

// manageUsedCategory()

// var categorys = id("com.wudaokou.hippo:id/scene_root_view").find()
// if( categorys ){
//     for (let i=0;i<categorys.length;i++){
//         let category = categorys[i]
//         log( JSON.stringify( getAllText(category) ))
        
//     }
// }
// exit()

// var categories_ = [];
// var categories = id("category_info_action_bar_tabs").findOne();
// if( categories ){
//     var all_Info = categories.children()
//     for (var i = 0; i < all_Info.length; i++) {
//         var d = all_Info[i];
//         // log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"',
//         //     "clickable->" + d.clickable(),'selected->' + selected(), "depth->" + d.depth(),)
//         if( d.desc() ){
//             categories_.push(d.desc().replace(/未选中，|已选中，/,""))
//         }
//     }
//     log(categories_)
// }
// // 调用选择界面（可根据业务需求调整调用位置，示例放在分类数据获取后）
// if (categories_.length > 0) {
//     selectCategory(); // 单次选择
//     // 如果需要允许多次选择，可使用循环：
//     while (dialogs.confirm("继续选择", `已经选择的分类\n${used_category}\n是否继续添加分类？`)) {
//         selectCategory();
//     }
// }
// log( used_category )

function getTag_(object){
    let tag_ = ""
    if ( object.id() && object.id().indexOf("tv_goods_tag") > -1 ){
        tag_ = object.desc()
    }
    if( object.children().length > 0 ){
        for (let i=0;i<object.children().length;i++){
            let child = object.children()[i]
            let tag__ = getTag_(child)
            if( tag__){
                tag_ = tag_ + '|' + tag__
            }
        }
    }
    return tag_
}



function pick(){
    while ( !appInfo.shop ){
        let shop = id("com.wudaokou.hippo:id/home_page_titlebar_shop_tag").textMatches('.*店').findOne(200);
        if (shop) {
            appInfo['shop'] = shop.text()
            log("店铺", appInfo['shop'])
        }else{
            back()
            sleep(3000)
        }
    }
    return appInfo['shop']
}

function getAllText(obj){
    const textInfo = {};
    try {
        if( obj.text() ){
            textInfo['text'] = obj.text()
        }
        if( obj.desc() ){
            textInfo['desc'] = obj.desc()
        }
        if( obj.id() ){
            textInfo['id'] = obj.id()
        }
        if( obj.children().length > 0 ){
            for (let i=0;i<obj.children().length;i++){
                let child = obj.children()[i]
                textInfo[i] = getAllText(child)
            }
        }
    } catch (error) {
        
    }

    return textInfo;
}

// 新增：解析商品信息的通用函数
function parseGoodsInfo(goodsJson) {
    const result = { title: null, tag: null, price: null };
    try {
 
          // 提取 title（child1 的 desc）
        if (goodsJson.child0.child0.child1.desc) {
            result.title = goodsJson.child0.child0.child1.desc;
        }
        // 提取 price（遍历所有 child 查找包含 ¥ 的 text/desc）
        // log('goodsJson', JSON.stringify(goodsJson.child0.child0))
        const children = goodsJson.child0.child0;
        let index = 0
        for (var key in children) {
            let child = children[key];
            index++
        

            if(index >= 2 && child.child0 && child.child0.id && child.child0.id == 'com.wudaokou.hippo:id/tv_goods_tag'){
                result.tag = child.child0.desc;
            }
  
            if(index >= 5 && child.text && child.text.includes('¥') ){
                result.price = child.text;
                break;
            }
        }
    } catch (error) {
        log('解析商品信息出错', error);
    }
    
    return result;
}
function getNextCategory(currentCategory) {
    const currentIndex = categories_.indexOf(currentCategory);
    // 若当前分类不存在于数组中，返回undefined
    if (currentIndex === -1) return undefined;
    // 计算下一个索引
    const nextIndex = currentIndex + 1;
    // 若下一个索引超出数组范围，返回undefined（可根据需求改为循环到第一个元素）
    if (nextIndex >= categories_.length) return undefined;
    return categories_[nextIndex];
}
// printAll()


function nextCategory2(){
    var list = textMatches(".{3,8}").drawingOrder(2).boundsInside(0, 0, device.width / 3, device.height).find()
    if (list) {
        for (let i = 0; i < list.length; i++) {
            let l = list[i]
            log(l.text(), l.depth())
            if( l.depth() == 26 ){
                var category2 = l.text()
                appInfo['category2'] = category2
                var up = textMatches(/.*查看下个分类/).findOne(200)
                if( up ){
                    if( up.bounds().centerY() < device.height ){
                        log('没有更多分类了')
                        f.click( list[i+1].bounds().centerX(), list[i+1].bounds().centerY(), 5, l.text() )
                        return true
                    }
                }
                break
            }
        }
    }
}


function todo(){
    
    // appInfo['shop'] = '福州'()


    var category = textMatches(categories_.join('|')).drawingOrder(5).findOne(200)
    if( category ){
        appInfo['category'] = category.text()
        log('category============', appInfo['category'])

        if (f.ms({ "textMatches":".*没有更多了.*" }) ){
            log("没有更多商品了")
            used_category.push(appInfo['category'])
            storage.put("used_category", used_category)
            sleep(5000)
        }

        if(used_category && used_category.indexOf(appInfo['category']) !== -1 ){
            log("已经选择过了")
            f.ms({ "textMatches": getNextCategory(appInfo['category']) }, true, 5)
            return true
        }
    }


    
    nextCategory2()

    var up = textMatches(/.*查看下个分类/).findOne(200)
    if( up ){
        if( up.bounds().centerY() < device.height ){
            nextCategory2()
            // return true
        }
    }

    var price = textMatches("¥.*").find()
    if (price) {
        for (let i = 0; i < price.length; i++) {
            let p = price[i]
            log('price', p.text(), '右底', p.bounds().bottom, '右高', p.bounds().top, '中心点', p.bounds().centerY(), '屏高', device.height)
            if( p.bounds().bottom < 0 || p.bounds().top < 0 ){
                log('在屏上')
                continue;
            }
            if( p.bounds().bottom > device.height || p.bounds().top > device.height ){
                log('屏下')
                continue;
            }
            var inputStr = JSON.stringify(getAllText(p.parent().parent().parent().parent().parent()))
            
            // log(inputStr)
            // 提取第一个text值（ttitle）
            var textRegex = /"text":"([^"]+?)"/;
            var ttitleMatch = inputStr.match(textRegex);
            var ttitle = ttitleMatch ? ttitleMatch[1].trim() : undefined; // 去除首尾空格

            // 提取所有¥价格（price_和vip）
            var priceRegex = /"¥([\d.]+?)"/g;
            var priceMatches = inputStr.match(priceRegex);
            var price_ = priceMatches ? priceMatches[0] : undefined; // 第一个¥价格（含¥符号）
            var vip = priceMatches && priceMatches.length >= 2 ? priceMatches[1] : undefined; // 第二个¥价格（VIP）

            log(ttitle, price_, vip)

            // exit()

            var postData = {
                "city": appInfo.shop,
                "shop": appInfo.shop,
                "category": appInfo.category,
                "category2": appInfo.category2,
                // "tag": getTag_(p.parent()).replace("||null|",""),
                "title": ttitle,
                "price": price_,
                "vip": vip,
            };
            if ( ttitle && ttitle.length > 6 ){
                // used_title.push(ttitle)
                f.postJson(postData)
            }
            

        }

        log("准备上滑")
        f.moveTo(0.5,0.9,0.5,0.2,1000)
        // f.moveTo(0.5,0.8,0.5,0.3,1000)
        // f.moveTo(0.5,0.8,0.5,0.3,1000)
    }

    if(! f.ms({"id":"com.pupumall.customer:id/tv_pull"})){
        log("列表页面，不抓")
        return
    }
    
}

var used_title = []
console.show();
// 设置日志窗口位置：右下角，设置为不可触摸
console.setPosition(device.width * 0.4, device.height * 0.4); // 中到右下角的位置
console.setSize(device.width * 0.3, device.height * 0.3); // 设置窗口大小
// console.setTouchable(false); // 设置为不可触摸

var change_key = false

manageUsedCategory()
while(true)  {
    // f.active("com.pupumall.customer", 5)
    if( !appInfo.shop ){
        if( f.ms({"id":"tv_place"})){
            try {
                appInfo.shop = id("tv_place").findOne(200).text()
            } catch (error) {
                
            }
        }else{
            back()
        }
    }

    if(appInfo.shop && f.ms({"id":"tv_place"}) ){
        f.ms({"text":"水果鲜花"}, true, 5)
    }

    try {
        todo()
    } catch (error) {
        // back()
        log('error', error)
        sleep(5000)
    }
}


// 
// f.active("com.pupumall.customer", 5)

// printAll()

// todo()

